package com.example.weblending.controlller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.weblending.domain.User;
import com.example.weblending.exception.GlobalException;
import com.example.weblending.service.UserService;
import com.example.weblending.utils.JwtUtils;
import com.example.weblending.utils.MD5;
import com.example.weblending.utils.Result;
import com.example.weblending.vo.PasswordVo;
import com.example.weblending.vo.UnsetPassword;
import com.example.weblending.vo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class LoginController {
    @Autowired
    private UserService userService;

    /**
     * 用户普通登录
     */
    @PostMapping("login")
    public Result LoginUser(@RequestBody User member){
        String token=userService.login(member);
        return Result.ok().data("token",token);
    }

    /**
     * 根据token获得用户信息
     */
    @GetMapping("info")
    public Result getMemberInfo(HttpServletRequest request){
        //调用jwt工具类
        String memberId= JwtUtils.getMemberIdByJwtToken(request);
        //调用数据库，根据用户id获取用户信息
        User member = userService.getById(memberId);
        return Result.ok().data(new UserInfo(member).getInfo());
    }

    /**
     * 修改用户信息
     */
    @PutMapping("info")
    public Result updateInfo(@RequestBody User user,HttpServletRequest request){
        //调用jwt工具类
        String memberId= JwtUtils.getMemberIdByJwtToken(request);
        User now=userService.getById(memberId);
        boolean success;
        if (user.getUid()!=-1){
            if(now.getPermission()!=1){
                throw new GlobalException(50008,"您无权限操作");
            }
        }else{
            user.setUid(now.getUid());
        }
        user.setPassword(null);
        user.setPermission(null);
        user.setAnalyzenum(null);
        user.setCleannum(null);
        user.setStatus(null);
        if(userService.isUserNameExist(user.getName())&&!user.getName().equals(now.getName())){
            throw new GlobalException(30001,"该登录名已经存在");
        }
        success=userService.updateById(user);
        return success?Result.ok():Result.error();
    }

    /**
     * 用户自己更新密码
     */
    @PutMapping("password")
    public Result updatePassword(@RequestBody PasswordVo passwordVo, HttpServletRequest request){
        if(!JwtUtils.checkToken(request)){
            throw new GlobalException(50008,"请重新登录");
        }
        String memberId= JwtUtils.getMemberIdByJwtToken(request);
        boolean success=userService.updatePassword(passwordVo,Integer.parseInt(memberId));
        return success?Result.ok():Result.error();
    }

    /**
     * 管理员新建用户，只能新建权限低自己一级的
     * 目前只有 系统管理员新增 普通管理员
     */
    @PostMapping("register")
    public Result register(@RequestBody User user, HttpServletRequest request){
        User opertor= JwtUtils.isOperator(request,userService);
        user.setPermission(opertor.getPermission()-1);
        boolean success=userService.register(user,true);
        return success?Result.ok().data("user",user):Result.error();
    }

    /**
     * 用户注册，只能注册普通用户
     */
    @PostMapping("signin")
    public Result register(@RequestBody User user){
        user.setPermission(0);
        boolean success=userService.register(user,false);
        return success?Result.ok().data("user",user):Result.error();
    }

    /**
     * 获得用户列表，只能获得权限低于自己一级的
     * 如 系统管理员只能看到普通管理员的列表
     */
    @GetMapping("list/{page}/{limit}")
    public Result list(@PathVariable long page, @PathVariable long limit, HttpServletRequest request){
        String memberId= JwtUtils.getMemberIdByJwtToken(request);
        User user=userService.getById(memberId);
        Page<User> userpage =userService.getListyId(page,limit,user);
        return Result.ok().data(userpage).data("item",userpage.getRecords());
    }




    /**
     * 禁用账号
     */
    @PostMapping("{uid}/disable")
    public Result disable(@PathVariable String uid, HttpServletRequest request){
        if(!JwtUtils.checkToken(request)){
            throw new GlobalException(50008,"请重新登录");
        }
        String memberId= JwtUtils.getMemberIdByJwtToken(request);
        boolean success = userService.setStaus(uid,memberId,1);
        return success?Result.ok():Result.error();
    }

    /**
     * 解封账号
     */
    @PostMapping("{uid}/enable")
    public Result enable(@PathVariable String uid, HttpServletRequest request){
        if(!JwtUtils.checkToken(request)){
            throw new GlobalException(50008,"请重新登录");
        }
        String memberId= JwtUtils.getMemberIdByJwtToken(request);
        boolean success = userService.setStaus(uid,memberId,0);
        return Result.ok();
    }

    /**
     * 使用一次性登录的方式登录
     */
    @PostMapping("reset/login")
    public Result resetLogin(@RequestBody UnsetPassword apply, HttpServletRequest request){
        String token=userService.resetLogin(apply);
        return Result.ok().data("token",token);
    }

    /**
     * 使用一次性登录的方式登录后更改密码
     */
    @PostMapping("reset/password")
    public Result resetPassword(@RequestBody PasswordVo passwordVo, HttpServletRequest request){
        User user=JwtUtils.checkUser(request,userService);
        user.setPassword(MD5.encrypt(passwordVo.getPassword()));
        return userService.updateById(user)?Result.ok():Result.error();
    }
}
